package cn.hamster3.mc.plugin.core.common.config;

import org.jetbrains.annotations.NotNull;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@SuppressWarnings({"unused", "VulnerableCodeUsages"})
public class YamlConfig extends ConfigSection {
    public static final Yaml YAML_LOADER = new Yaml();

    public YamlConfig() {
        super();
    }

    public YamlConfig(@NotNull Map<String, Object> map) {
        super(map);
    }

    public static YamlConfig load(@NotNull File file) throws IOException {
        try (FileInputStream stream = new FileInputStream(file)) {
            try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                return load(reader);
            }
        }
    }

    public static YamlConfig load(@NotNull Reader reader) {
        Map<String, Object> load = YAML_LOADER.load(reader);
        return new YamlConfig(load);
    }

    public void save(@NotNull File file) throws IOException {
        try (FileOutputStream stream = new FileOutputStream(file)) {
            try (OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
                YAML_LOADER.dump(map, writer);
            }
        }
    }
}
